﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Globalization;

namespace Unleashed.AutoUpdate.IO
{
    /// <summary>
    /// IO File operations
    /// </summary>
    public static class File
    {
        public static void CopyAndCheck(string sourcePath, string targetPath)
        {
            System.IO.File.Copy(sourcePath, targetPath, true);

            if (!Compare(sourcePath, targetPath))
            {
                throw new FileLoadException(String.Format(CultureInfo.InvariantCulture, "File {0} is not equal to {1} after copying", sourcePath));
            }
        }

        /// <summary>
        /// Compare two files byte by byte
        /// </summary>
        /// <param name="path1">path of the first file</param>
        /// <param name="path2">path of the second file</param>
        /// <returns>true if the files are identical, otherwise false</returns>
        public static bool Compare(string path1, string path2)
        {
            return ChecksumSha1(path1) == ChecksumSha1(path2);
        }

        /// <summary>
        /// Calculates MD5 checksum for a file
        /// </summary>
        /// <param name="path">path of the file</param>
        /// <returns>Base64 encoded checksum</returns>
        public static string ChecksumSha1(string path)
        {
            byte[] hash = null;

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                hash = sha1.ComputeHash(fs);

                fs.Close();
            }

            return Convert.ToBase64String(hash);
        }
    }
}